package team.seekers.hula.system.ratelimit.filter;

import cn.hutool.core.collection.ConcurrentHashSet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import team.seekers.hula.common.config.FilterProperties;
import team.seekers.hula.common.entity.result.ApiExceptionEnum;
import team.seekers.hula.common.entity.result.ApiException;
import team.seekers.hula.system.ratelimit.limiter.RequestRateLimiter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * 限流过滤器，通过URI限流
 *
 * @author GH
 */
@Slf4j
@Component
@EnableConfigurationProperties({FilterProperties.class})
public class GlobalLimitFilter extends OncePerRequestFilter implements Ordered {

    protected final Set<String> limitedUrls = new ConcurrentHashSet<>();

    @Autowired
    protected FilterProperties filterProp;

    @Autowired
    private RequestRateLimiter requestRateLimiter;

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    /**
     * Make sure that this filter takes precedence over StripFilter
     */
    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String requestUrl = request.getRequestURI();
        rateFilter(request, response, chain, requestUrl, requestUrl, 1, filterProp.getGlobalLimitPaths());
    }

    public void rateFilter(HttpServletRequest request,
                           HttpServletResponse response,
                           FilterChain chain,
                           String requestUrl,
                           String id,
                           int requested,
                           Map<String, Integer> rateConfig) throws ServletException, IOException {
        if (!requestRateLimiter.isAllowed(requestUrl, id, rateConfig, requested)) {
            limitedUrls.add(requestUrl);
        } else {
            limitedUrls.remove(requestUrl);
        }
        if (limitedUrls.contains(requestUrl)) {
            log.debug("{}Limit for url: {} from: {}", requestUrl.equals(id) ? "Global" : "User", requestUrl, id);
            resolver.resolveException(request, response, null, new ApiException(
                    ApiExceptionEnum.SERVER_BUSY,
                    "您的操作请求过于频繁，已被服务器限流，请稍等片刻后重试！！（如为异常误报，请联系管理员）"));
            return;
        }
        chain.doFilter(request, response);
    }
}
